from django.http import JsonResponse, HttpResponse
from realize.serializers import *
from rest_framework.decorators import api_view
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi


@swagger_auto_schema(
    method='get',
    operation_summary='数据统计 ｜ 获取基站、台站、资产统计',
    manual_parameters=[
        openapi.Parameter(
            name='type', in_=openapi.IN_QUERY,
            type=openapi.TYPE_STRING,
            enum=['station', 'fa_station', 'stuff'],
            description="Type of request"
        )
    ]
)
@api_view(['GET'])
def getCountNumber(request):
    type = request.GET['type']
    count, dist = 0, {}
    categoryDict = {}

    if type == 'station':
        count = Station.objects.count()
        queryList = Station.objects.all()

    elif type == 'fa_station':
        count = FaStation.objects.count()
        queryList = FaStation.objects.all()
    elif type == 'stuff':
        queryList = Stuff.objects.all()
        serializer = StuffSerializer(queryList, many=True)

        return JsonResponse(serializer.data, safe=False)

    for item in queryList:
        print(item.category)

        key = item.category.category_name
        if key not in categoryDict:
            categoryDict[key] = 1
        else:
            categoryDict[key] += 1

    finalDict = {'total': count, 'category': categoryDict}
    return JsonResponse(finalDict)


@swagger_auto_schema(
    method='get',
    operation_summary='台站查询',
    manual_parameters=[
        openapi.Parameter(
            name='start', in_=openapi.IN_QUERY,
            type=openapi.TYPE_STRING,
            description="开始频率"
        ),
        openapi.Parameter(
            name='end', in_=openapi.IN_QUERY,
            type=openapi.TYPE_STRING,
            description="结束频率"
        ),
        openapi.Parameter(
            name='category', in_=openapi.IN_QUERY,
            type=openapi.TYPE_STRING,
            description="站台部门",
            enum=['null', '水路', '航空', '其他', '铁路', '电信'],
        )
    ]
)
@api_view(['GET'])
def query_station(request):
    category = request.GET['category']
    start = int(request.GET['start'])
    end = int(request.GET['end'])

    if category != 'null':
        objects = Station.objects.filter(
            frequency__range=[start, end],
            category__category_name=category
        )
    else:
        objects = Station.objects.filter(
            frequency__range=[start, end],
        )

    serializer = StationSerializer(objects.all(), many=True)
    dist = {'total': objects.count(), 'dataList': serializer.data}
    return JsonResponse(dist, safe=False)
